package com.zoe.onelink.auth.autoconfigure;

import com.zoe.onelink.auth.component.OneLinkBearerTokenExtractor;
import com.zoe.onelink.auth.component.ResourceAuthExceptionEntryPoint;
import com.zoe.onelink.auth.properties.AuthProperties;
import com.zoe.onelink.common.constant.WebConstant;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2018</p>
 * <p>公司: 智业软件</p>
 *
 * @author LinHongKai
 * @date 2022-03-13 8:53
 */
@Slf4j
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Import({ResourceServerAutoConfiguration.class, EndPointConfiguration.class})
@RequiredArgsConstructor
public class OneLinkResourceServerAutoConfiguration extends ResourceServerConfigurerAdapter {

    private final ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint;

    private final AuthProperties authProperties;

    private final OneLinkBearerTokenExtractor oneLinkBearerTokenExtractor;

    private final ResourceServerTokenServices resourceServerTokenServices;

    /**
     * 默认的配置，对外暴露
     * @param httpSecurity
     */
    @Override
    @SneakyThrows
    public void configure(HttpSecurity httpSecurity) {
        // 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        httpSecurity.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
        // 暴露静态资源
        registry.antMatchers(WebConstant.INSENSITIVE_URLS).permitAll();
        authProperties.getIgnoreUrls().forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated().and().csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint)
                .tokenExtractor(oneLinkBearerTokenExtractor)
                .tokenServices(resourceServerTokenServices);
    }
}
